import {Request, RequestQuery, ResponseObject, ResponseToolkit} from "hapi";
import AuthService from "../services/auth";
import {IUser} from "@/models/user";

export default class AuthController {
    // email注册
    static async emailRegister(request: Request, h: ResponseToolkit): Promise<ResponseObject> {
        let user = request.payload as IUser
        console.log(request.url.origin);
        try {
            let res = await AuthService.emailRegister(user.username, user.password, request)
            return h.response(res).code(201)
        } catch (e) {
            return h.response(e).code(422)
        }
    }

    // 邮箱验证
    static async emailAuth(request: Request, h: ResponseToolkit): Promise<ResponseObject> {
        let query: RequestQuery = request.query;
        let res = await AuthService.emailAuth(query['id'] as string, query['authCode'] as string)
        return h.response(res).code(200)
    }

    // 登录
    static async login(request: Request, h: ResponseToolkit): Promise<ResponseObject> {
        let user = request.payload as IUser
        try {
            let res = await AuthService.login(user.username, user.password)
            return h.response(res).code(200)
        } catch (e) {
            return h.response(e).code(500)
        }
    }

    static async test(request: Request, h: ResponseToolkit) {
        return h.response('I need token').code(200)
    }
}
